package com.shujia;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class MyMap implements Runnable {
    private File file;
    private int index;
    private BufferedWriter bw;
    private BufferedReader br;

    MyMap(File file, int index) {
        this.file = file;
        this.index = index;
    }


    @Override
    public void run() {
        try {
            /**
             * 使用IO流读取文件，一行一行的读取，
             * 每次读取去校验一下map中是否已经存在相同的键，
             * 如果存在，该键的value值就+1，不存在的话，将该班级作为键保存，值为1.
             */
            //读取文件
            br = new BufferedReader(new FileReader(file.getAbsolutePath()));
            HashMap<String, Integer> map = new HashMap<>();

            String line = null;
            while ((line = br.readLine()) != null) {
                //对字符串进行切分，获取到班级
                String clazz = line.split(",")[4];
                //往map集合中添加
                if (!map.containsKey(clazz)) {
                    map.put(clazz, 1);
                } else {
                    map.put(clazz, map.get(clazz) + 1);
                }
            }

            //统计完后将集合中的结果写入到文件中
            bw = new BufferedWriter(new FileWriter("data/parts/part--" + index));
            //遍历集合
            Set<Map.Entry<String, Integer>> entries = map.entrySet();
            for (Map.Entry<String, Integer> entry : entries) {
                String clazz = entry.getKey();
                Integer numbers = entry.getValue();
                bw.write(clazz + ":" + numbers);
                bw.newLine();
                bw.flush();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
